<?php
/**
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

/**
 * Created by PhpStorm.
 * User: poptser
 * Date: 2017/6/16
 * Time: 11:21
 */
namespace SDXApi\Controller;
use SDXApi\Service\BonusService;
use Think\Controller;
use Think\Exception;
use Think\Model;

class OperationController extends Controller
{
    public function _initialize(){
        header("Access-Control-Allow-Origin: *");
    }

    /**
     * 获取到昨天登录的用户
     */
    public function auto_give_bonus(){
        exit(0);
        set_time_limit(0);
        dump(local_date("Y-m-d H:i:s",time()));
        header("Content-type: text/html; charset=utf-8");
        echo "已开始运行.........<br/>";
        //M("gift_gct")->where(array("user_id"=>5726))->delete();
        $auto_cache = S("auto_give_bonus");
        if($auto_cache){
            return false;
        }else{
            S("auto_give_bonus",1,600);
        }
        if(date("H")!=16&&date("i")!=00){
            //exit("运行时间错误");
        }
        //查询昨天有浏览记录绑定手机用户
        $yesterday_address = M()->table(array('sdx_user_behavior_browse'=>'uba','sdx_user_address'=>'u'))
            ->where("TO_DAYS(from_unixtime(uba.add_time)) = TO_DAYS(from_unixtime(unix_timestamp()))-1 AND uba.uid = u.user_id AND u.mobile !=''")
            ->field("distinct(uba.uid)")->select();

        $give_address = array();
        foreach ($yesterday_address as $value){
            $give_address[] = $value['uid'];
        }


        //查询昨天有登录标记绑定手机用户
        $yesterday_address_login = M()->table(array('sdx_user_behavior_address'=>'uba','sdx_user_address'=>'u'))
            ->where("uba.type = 'login' AND TO_DAYS(from_unixtime(uba.add_time)) = TO_DAYS(from_unixtime(unix_timestamp()))-1 AND uba.uid = u.user_id AND u.mobile !=''")
            ->field("distinct(uba.uid)")->select();
        //dump(M()->getLastSql());
        $give_address_login = array();
        foreach ($yesterday_address_login as $value){
            $give_address_login[] = $value['uid'];
        }

        //dump($yesterday_address);
        //查询昨天有登录标记地址中有手机用户
        $yesterday_login_login = M()->table(array('sdx_user_behavior_address'=>'uba','sdx_users'=>'u'))
            ->where("uba.type = 'login' AND TO_DAYS(from_unixtime(uba.add_time)) = TO_DAYS(from_unixtime(unix_timestamp()))-1 AND uba.uid = u.user_id AND u.mobile_phone !=''")
            ->field("distinct(uba.uid)")->select();
        $give_login_login = array();
        foreach ($yesterday_login_login as $value){
            $give_login_login[] = $value['uid'];
        }
        //dump($yesterday_address);
        //查询有浏览商品记录浏览商品记录
        $yesterday_login = M()->table(array('sdx_user_behavior_browse'=>'uba','sdx_users'=>'u'))
            ->where("TO_DAYS(from_unixtime(uba.add_time)) = TO_DAYS(from_unixtime(unix_timestamp()))-1 AND uba.uid = u.user_id AND u.mobile_phone !=''")
            ->field("distinct(uba.uid)")->select();
        $give_login = array();
        foreach ($yesterday_login as $value){
            $give_login[] = $value['uid'];
        }
        //dump($yesterday_login);
        $old_give_array = array_unique(array_merge($give_login,$give_address,$give_login_login,$give_address_login));

        //dump($old_give_array);
//        exit();
        $array_give = array();
        foreach ($old_give_array as $value){
            //查询此用户今天是否送过红包
            $is_give = M("gift_gct")->where("TO_DAYS(from_unixtime(add_time)) = TO_DAYS(from_unixtime(unix_timestamp()-28800)) AND type = 3 AND user_id=".$value)->count("id");

            if($is_give==0) {
                $array_give[] =$value;
            }
        }
        $array_give = array_unique($array_give);
        //dump($array_give);
        //exit();
        if(count($array_give)>0){
            $this->send_dingtalk_ts("正在发送签到红包信息...");
            $this->users_first($array_give,144);   //判断首次登录用户赠送红包，并返回非首次登录
            $this->users_continued_5($array_give,145);   //判断连续签到5次
            $this->users_continued_10($array_give,146);   //判断连续签到10次
            $this->users_total_15($array_give,147);   //判断累计签到15次
            $this->users_total_25($array_give,148);   //判断累计签到25次
        }
    }
    /**
     * 累计十五次
     */
    public function users_total_15($array_give,$bonus_type_id){
        $now_day = local_date('d',gmtime());
        if($now_day<15){
            return false;   //本月还不足十五日，直接跳过
        }
        foreach ($array_give as $key=>$value){
            //判断本月是否领取过 累计15日红包了
            $is_continued_num_25 = array();
            $yesterday_address_25 = array();
            $yesterday_login_login_25 = array();
            $yesterday_login_25 = array();

            $is_give = M("gift_gct")->
            where("from_unixtime(add_time,'%Y%m') = from_unixtime(unix_timestamp()-28800,'%Y%m') and money = ".$bonus_type_id." and type = 3 AND user_id=".$value)
                ->field("id")->count();
            if($is_give==0) {
                //本月还未领取累计15日连续红包，判断之，是否累计了15日了
                $is_continued_num = M()->table(array('sdx_user_behavior_address'=>'uba','sdx_users'=>'u'))
                    ->where("from_unixtime(uba.add_time, '%Y%m') = from_unixtime(unix_timestamp(), '%Y%m')
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))!= TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))
   AND uba.uid= u.user_id AND u.mobile_phone!= '' AND u.user_id= ".$value)->field("from_unixtime(uba.add_time,'%Y%m%d') as add_times")
                    ->group("from_unixtime(uba.add_time,'%Y-%m-%d')")
                    ->select();
                foreach ($is_continued_num as $values){
                    $is_continued_num_25[] = $values['add_times'];
                }
                $yesterday_address = M()->table(array('sdx_user_behavior_browse'=>'uba','sdx_user_address'=>'u'))
                    ->where("from_unixtime(uba.add_time, '%Y%m') = from_unixtime(unix_timestamp(), '%Y%m')
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))!= TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))
   AND uba.uid= u.user_id AND u.mobile!= '' AND u.user_id= ".$value)->field("from_unixtime(uba.add_time,'%Y%m%d') as add_times")
                    ->group("from_unixtime(uba.add_time,'%Y-%m-%d')")
                    ->select();
                foreach ($yesterday_address as $values){
                    $yesterday_address_25[] = $values['add_times'];
                }

                $yesterday_login_login = M()->table(array('sdx_user_behavior_address'=>'uba','sdx_user_address'=>'u'))
                    ->where("from_unixtime(uba.add_time, '%Y%m') = from_unixtime(unix_timestamp(), '%Y%m')
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))!= TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))
   AND uba.uid= u.user_id AND u.mobile!= '' AND u.user_id= ".$value)->field("from_unixtime(uba.add_time,'%Y%m%d') as add_times")
                    ->group("from_unixtime(uba.add_time,'%Y-%m-%d')")
                    ->select();
                foreach ($yesterday_login_login as $values){
                    $yesterday_login_login_25[] = $values['add_times'];
                }

                $yesterday_login = M()->table(array('sdx_user_behavior_browse'=>'uba','sdx_users'=>'u'))
                    ->where("from_unixtime(uba.add_time, '%Y%m') = from_unixtime(unix_timestamp(), '%Y%m')
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))!= TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))
   AND uba.uid= u.user_id AND u.mobile_phone!= '' AND u.user_id= ".$value)
                    ->group("from_unixtime(uba.add_time,'%Y-%m-%d')")->field("from_unixtime(uba.add_time,'%Y%m%d') as add_times")
                    ->select();
                foreach ($yesterday_login as $values){
                    $yesterday_login_25[] = $values['add_times'];
                }

                $old_give_array = array_unique(array_merge($is_continued_num_25,$yesterday_address_25,$yesterday_login_login_25,$yesterday_login_25));
                if(count($old_give_array)==15){
                    //已连续登陆15日，赠送红包
                    $total_15_give[] =$value;
                }
            }
        }
        if(count($total_15_give)>0){
            $this->give_bonus($total_15_give,$bonus_type_id); //赠送累计15日登录红包
        }
    }
    /**
     * 连续签到十次
     */
    public function users_continued_10($array_give,$bonus_type_id){
        $now_day = local_date('d',gmtime());
        if($now_day<10){
            return false;   //本月还不足十日，直接跳过
        }
        foreach ($array_give as $key=>$value){
            //判断本月是否领取过 连续10日红包了
            $is_continued_num_25 = array();
            $yesterday_address_25 = array();
            $yesterday_login_login_25 = array();
            $yesterday_login_25 = array();
            $is_give = M("gift_gct")->
            where("from_unixtime(add_time,'%Y%m') = from_unixtime(unix_timestamp()-28800,'%Y%m') and money = ".$bonus_type_id." and type = 3 AND user_id=".$value)
                ->field("id")->count();
            if($is_give==0) {
                //本月还未领取10日连续红包，判断之，是否连续10日了
                $is_continued_num = M()->table(array('sdx_user_behavior_address'=>'uba','sdx_users'=>'u'))
                    ->where("from_unixtime(uba.add_time, '%Y%m') = from_unixtime(unix_timestamp(), '%Y%m')
   AND TO_DAYS(from_unixtime(uba.add_time))< TO_DAYS(from_unixtime(unix_timestamp()))
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))> TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))-11 AND uba.uid= u.user_id
   AND u.mobile_phone!= '' AND u.user_id= ".$value)->group("from_unixtime(uba.add_time,'%Y-%m-%d')")
                    ->field("from_unixtime(uba.add_time,'%Y%m%d') as add_times")
                    ->select();
                foreach ($is_continued_num as $values){
                    $is_continued_num_25[] = $values['add_times'];
                }

                $yesterday_address = M()->table(array('sdx_user_behavior_browse'=>'uba','sdx_user_address'=>'u'))
                    ->where("from_unixtime(uba.add_time, '%Y%m') = from_unixtime(unix_timestamp(), '%Y%m')
   AND TO_DAYS(from_unixtime(uba.add_time))< TO_DAYS(from_unixtime(unix_timestamp()))
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))> TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))-11 AND uba.uid= u.user_id
   AND u.mobile!= '' AND u.user_id= ".$value)->group("from_unixtime(uba.add_time,'%Y-%m-%d')")
                    ->field("from_unixtime(uba.add_time,'%Y%m%d') as add_times")
                    ->select();
                foreach ($yesterday_address as $values){
                    $yesterday_address_25[] = $values['add_times'];
                }

                $yesterday_login_login = M()->table(array('sdx_user_behavior_address'=>'uba','sdx_user_address'=>'u'))
                    ->where("from_unixtime(uba.add_time, '%Y%m') = from_unixtime(unix_timestamp(), '%Y%m')
   AND TO_DAYS(from_unixtime(uba.add_time))< TO_DAYS(from_unixtime(unix_timestamp()))
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))> TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))-11 AND uba.uid= u.user_id
   AND u.mobile!= '' AND u.user_id= ".$value)->group("from_unixtime(uba.add_time,'%Y-%m-%d')")
                    ->field("from_unixtime(uba.add_time,'%Y%m%d') as add_times")
                    ->select();
                foreach ($yesterday_login_login as $values){
                    $yesterday_login_login_25[] = $values['add_times'];
                }

                $yesterday_login = M()->table(array('sdx_user_behavior_browse'=>'uba','sdx_users'=>'u'))
                    ->where("from_unixtime(uba.add_time, '%Y%m') = from_unixtime(unix_timestamp(), '%Y%m')
   AND TO_DAYS(from_unixtime(uba.add_time))< TO_DAYS(from_unixtime(unix_timestamp()))
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))> TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))-11 AND uba.uid= u.user_id
   AND u.mobile_phone!= '' AND u.user_id= ".$value)->group("from_unixtime(uba.add_time,'%Y-%m-%d')")
                    ->field("from_unixtime(uba.add_time,'%Y%m%d') as add_times")
                    ->select();
                foreach ($yesterday_login as $values){
                    $yesterday_login_25[] = $values['add_times'];
                }
                $old_give_array = array_unique(array_merge($is_continued_num_25,$yesterday_address_25,$yesterday_login_login_25,$yesterday_login_25));
                if(count($old_give_array)==10){
                    //已连续登陆10日，赠送红包
                    $continued_10_give[] =$value;
                }
            }
        }
        if(count($continued_10_give)>0){
            $this->give_bonus($continued_10_give,$bonus_type_id); //赠送连续10日登录红包
        }

    }
    /**
     * 连续签到五次
     */
    public function users_continued_5($array_give,$bonus_type_id){
        $now_day = local_date('d',gmtime());
        if($now_day<5){
            return false;   //本月还不足五日，直接跳过
        }
        foreach ($array_give as $key=>$value){
            //判断本月是否领取过 连续5日红包了
            $is_give = M("gift_gct")->
            where("from_unixtime(add_time,'%Y%m') = from_unixtime(unix_timestamp()-28800,'%Y%m') and money = ".$bonus_type_id." and type = 3 AND user_id=".$value)
                ->field("id")->count();

            if($is_give==0) {
                $is_continued_num_25 = array();
                $yesterday_address_25 = array();
                $yesterday_login_login_25 = array();
                $yesterday_login_25 = array();
                //本月还未领取5日连续红包，判断之，是否连续5日了
                $is_continued_num = M()->table(array('sdx_user_behavior_address'=>'uba','sdx_users'=>'u'))
                    ->where("from_unixtime(uba.add_time, '%Y%m') = from_unixtime(unix_timestamp(), '%Y%m')
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))< TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))> TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))-6 AND uba.uid= u.user_id
   AND u.mobile_phone!= '' AND u.user_id= ".$value)->group("from_unixtime(uba.add_time,'%Y-%m-%d')")
                    ->field("from_unixtime(uba.add_time,'%Y%m%d') as add_times")
                    ->select();
                foreach ($is_continued_num as $values){
                    $is_continued_num_25[] = $values['add_times'];
                }


                $yesterday_address = M()->table(array('sdx_user_behavior_browse'=>'uba','sdx_user_address'=>'u'))
                    ->where("from_unixtime(uba.add_time, '%Y%m') = from_unixtime(unix_timestamp(), '%Y%m')
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))< TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))> TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))-6 AND uba.uid= u.user_id
   AND u.mobile!= '' AND u.user_id= ".$value)->group("from_unixtime(uba.add_time,'%Y-%m-%d')")
                    ->field("from_unixtime(uba.add_time,'%Y%m%d') as add_times")
                    ->select();
                foreach ($yesterday_address as $values){
                    $yesterday_address_25[] = $values['add_times'];
                }

                $yesterday_login_login = M()->table(array('sdx_user_behavior_address'=>'uba','sdx_user_address'=>'u'))
                    ->where("from_unixtime(uba.add_time, '%Y%m') = from_unixtime(unix_timestamp(), '%Y%m')
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))< TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))> TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))-6 AND uba.uid= u.user_id
   AND u.mobile!= '' AND u.user_id= ".$value)->group("from_unixtime(uba.add_time,'%Y-%m-%d')")
                    ->field("from_unixtime(uba.add_time,'%Y%m%d') as add_times")
                    ->select();
                foreach ($yesterday_login_login as $values){
                    $yesterday_login_login_25[] = $values['add_times'];
                }
                $yesterday_login = M()->table(array('sdx_user_behavior_browse'=>'uba','sdx_users'=>'u'))
                    ->where("from_unixtime(uba.add_time, '%Y%m') = from_unixtime(unix_timestamp(), '%Y%m')
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))< TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))
   AND TO_DAYS(from_unixtime(uba.add_time, '%Y%m%d'))> TO_DAYS(from_unixtime(unix_timestamp(), '%Y%m%d'))-6 AND uba.uid= u.user_id
   AND u.mobile_phone!= '' AND u.user_id= ".$value)->group("from_unixtime(uba.add_time,'%Y-%m-%d')")
                    ->field("from_unixtime(uba.add_time,'%Y%m%d') as add_times")
                    ->select();
                foreach ($yesterday_login as $values){
                    $yesterday_login_25[] = $values['add_times'];
                }
                $old_give_array = array_unique(array_merge($is_continued_num_25,$yesterday_address_25,$yesterday_login_login_25,$yesterday_login_25));

                if(count($old_give_array)==5){
                    //已连续登陆5日，赠送红包
                    $continued_5_give[] =$value;
                }
            }
        };
        if(count($continued_5_give)>0){
            $this->give_bonus($continued_5_give,$bonus_type_id); //赠送连续5日登录红包
        }

    }


    /**
     * 首次登录用户赠送
     * @param $array_give
     * @return mixed
     */
    public function users_first($array_give,$bonus_id){
        foreach ($array_give as $key=>$value){
            $is_give = M("gift_gct")->where("type = 3 AND user_id=".$value)->count("id");
            if($is_give==0) {
                //首次登录用户-给包包，发信信
                $first_give[] =$value;
                unset($array_give[$key]);
            }
        }
        if(count($first_give)>0){
            $this->give_bonus($first_give,$bonus_id); //赠送首次登录红包
        }

        //发送信息
        return $array_give;
    }


    /**
     * 赠送指定红包
     * @param $user_array
     * @param $bonus_id
     */
    public function give_bonus($user_array, $bonus_id){

        foreach ($user_array as $key=>$value){
            $bonus_id_f = M("user_bonus")->where(array("bonus_type_id"=>$bonus_id,"user_id"=>0))
                ->find();
            if($bonus_id_f){
                $effective_days = M("bonus_type")->where(array("type_id"=>$bonus_id,"user_id"=>0))
                    ->getField("effective_days");
                if($effective_days>0){
                    $data['deadline'] = gmtime() + $effective_days*24*3600;
                }
                $data['user_id'] = $value;
                $data['get_time'] = gmtime();
                M("user_bonus")->where(array("bonus_id"=>$bonus_id_f['bonus_id']))->save($data);

                $dataList[] = array(
                    'user_id'=>$value,
                    'money'=>$bonus_id,     //赠送红包 ID
                    'type'=>3,  //登录奖励送 红包
                    'add_time'=>gmtime()
                );

                $user_action_data[] = array(
                    "action_name" => "System",
                    "action_time" => gmtime(),
                    "action_type" => "登录奖励 [ ".date("Y-m-d",strtotime("-1 day"))." ]",
                    "user_id" => $value,
                    "old_value" => "",
                    "new_value" => "获得红包：".$bonus_id_f['bonus_sn'],
                );
            }
        }
        M("gift_gct")->addAll($dataList);
        M("user_action")->addAll($user_action_data);
        $give_phone = array();
        //发送信息
        foreach ($user_array as $key=>$value){
            //发送信息
            $mobile_phone = M("users")->where(array("user_id"=>$value))->getField("mobile_phone");
            if($mobile_phone){
                //是绑定手机号
                $give_phone[$value] = $mobile_phone;
            }else{
                //未绑定手机号/查询默认地址中的手机号
                $give_phone[$value] = M("user_address")->where(array("user_id"=>$value,"default"=>1))->getField("mobile");
            }
        }

//首次签到5元红包ID：144
//连签5次5元红包ID:145
//连签10次10元红包ID：146
//累积签15次15元红包ID:147
        switch ($bonus_id){
            case 144:
                $title_msg = "首次签到，赠送一个5元红包";
                $continuousSignAcount=1;
                break;
            case 145:
                $title_msg = "连续签到5天，赠送一个5元红包";
                $continuousSignAcount=5;
                break;
            case 146:
                $title_msg = "连续签到10天，赠送一个10元红包";
                $continuousSignAcount=10;
                break;
            case 147:
                $title_msg = "累计签到15天，赠送一个15元红包";
                $continuousSignAcount=15;
                break;
            case 148:
                $title_msg = "累计签到25天，";
                $continuousSignAcount=25;
                break;
        }

        $msg_opt = M("mail_templates")->where(array("template_code"=>"daily_rewards"))->getField("msg_opt");

        $msg_opt = str_replace("\r\n",",",$msg_opt);
        $msg_opt = explode(",",$msg_opt);

        foreach ($give_phone as $key=>$phone){
            //发送信息到用户手机
            //echo "手机:".$value."</br>";
            if(!empty($phone)){
                $wechat_param=$this->get_daily_rewards_wechat_param($phone,$title_msg,$continuousSignAcount);
                A("Smsapi")->send_message_api("daily_rewards",$phone,$msg_opt[0],0,0,0,$key,array("goods_title"=>$msg_opt[1]),null,$wechat_param);
            }
        }
    }


    /**获取微信推送参数
     * @param $phone
     * @param $title_msg
     * @param $continuousSignAcount
     * @return mixed
     */
    private function get_daily_rewards_wechat_param($phone,$title_msg,$continuousSignAcount){
        $wechat_param['url']="https://w.shidexian.com/?index#/index?utm_source=GZHmrjl";
        $wechat_param['first']='尊敬的小主，您昨日的登录福利已发放，请注意查收~每天登录每天送。';
        $wechat_param['keyword1']=$phone;
        $wechat_param['keyword2']=date("Y-m-d",strtotime("-1 day"));
        $wechat_param['keyword3']=$title_msg;
        $wechat_param['keyword4']=$continuousSignAcount.'天';
        return $wechat_param;
    }




    /**
     * 领取过登录奖励，但是最近没有上线，则短信提醒  短信提醒频率为3天一次
     */
    public function urge_online(){
        set_time_limit(0);
        $auto_cache = S("auto_give_bonus");
        if($auto_cache){
            return false;
        }else{
            S("auto_give_bonus",1,600);
        }
        if(date("H:i")!="21:00"){
            exit("运行时间错误");
        }
        $i=0;

        dump(local_date("Y-m-d H:i:s",gmtime()));

        $msg_opt = M("mail_templates")->where(array("template_code"=>"urge_online"))->getField("msg_opt");
        $msg_opt = str_replace("\r\n",",",$msg_opt);
        $msg_opt = explode(",",$msg_opt);

        try{
            $this->send_dingtalk_ts("正在发送，连续登陆活动中的，未登陆提醒");
        }catch (Exception $e){

        }




        //查询昨天有登录标记绑定手机用户
        //$is_give = M()->table(array('sdx_user_behavior_address' => 'uba', 'sdx_user_address' => 'u'))
        //   ->where("uba.type = 'login' AND uba.uid = u.user_id AND u.mobile !=''")
        //   ->field("uba.uid,max(uba.add_time) as add_time")->group("uba.uid")->select();
        $is_give = M("gift_gct")->field('user_id,max(add_time) as add_time')->where(array("type"=>3))->group("user_id")->select();

        $yesterday_login_login = M()->table(array('sdx_user_behavior_address'=>'uba','sdx_users'=>'u'))
            ->where("uba.type = 'login' AND uba.uid = u.user_id AND u.mobile_phone !=''")
            ->field("u.user_id,max(add_time) as add_time")->group("u.user_id")->select();


        $i = 0;
        $new_array =array();

        $phone_array =array();
        foreach ($yesterday_login_login as $key=>$value){
            $date=floor((gmtime()-$value['add_time'])/86400);    //已经未发奖励
            if($date>0 &&$date%7==0){
                $num = M("message_log")->where("user_id = {$value['user_id']} AND templates_id = 54 AND TO_DAYS(send_time) = TO_DAYS(NOW())")->count();
                $num_gift = M("gift_gct")->where("user_id = {$value['user_id']}")->count();
                if($num==0&&$num_gift>0){
                    $new_array[] = $value['user_id'];
                    $now_phone = M("users")->where(array("user_id"=>$value['user_id']))->getField("mobile_phone");
                    if($now_phone){
                        //是绑定手机号
                        $phone_array[] = $now_phone;
                        $wechat_param=$this->get_wechat_param($value['user_id']);
                        A("Smsapi")->send_message_api("urge_online",$now_phone,'促进上线',0,0,0,$value['user_id'],array("goods_title"=>$msg_opt[0]),null,$wechat_param);
                    }else{
                        //未绑定手机号/查询默认地址中的手机号
                        $give_phone = M("user_address")->where(array("user_id"=>$value['user_id'],"default"=>1))->getField("mobile");
                        if(empty($give_phone)){
                            $give_phone = M("user_address")->where("user_id = {$value['user_id']} and mobile!=''")->getField("mobile");
                        }
                        if($give_phone){
                            $phone_array[] = $give_phone;
                            $wechat_param=$this->get_wechat_param($value['user_id']);
                            A("Smsapi")->send_message_api("urge_online",$give_phone,'促进上线',0,0,0,$value['user_id'],array("goods_title"=>$msg_opt[0]),null,$wechat_param);
                        }
                    }
                }
            }
        }


    }

    /**获取提醒上线微信推送参数
     * @param $uid
     * @return mixed
     */
    private function get_wechat_param($uid){

        $money = M("gift_gct")->where(array("type"=>3))->order("add_time desc")->getField("money");
        $bonusDay=1;
        $bonusMoney=5;
        switch ($money){
            case 144:
                $bonusDay=1;
                $bonusMoney=5;
                break;
            case 145:
                $bonusDay=5;
                $bonusMoney=5;
                break;
            case 146:
                $bonusDay=10;
                $bonusMoney=10;
                break;
            case 147:
                $bonusDay=15;
                $bonusMoney=15;
                break;
        }
        $sign_in_count=$this->get_sign_in_count($uid);
        $betweenSecond=strtotime(date("Y-m-d"))-strtotime($sign_in_count['lastSignDate']);
        $dayS=$betweenSecond/(24*60*60);


        $wechat_param['keyword1']="您已经".$dayS."天未登录签到，连续登录".$bonusDay."天可得".$bonusMoney."元红包哦！";
        $wechat_param['keyword2']=$sign_in_count['lastSignDate'];


        return $wechat_param;
    }

    /**获取用户签到次数/最后签到日期
     * @param $uid
     * @return mixed
     */
    private function get_sign_in_count($uid){
        $is_continued_num_25 = array();
        $yesterday_address_25 = array();

        //本月还未领取10日连续红包，判断之，是否连续10日了
        $is_continued_num = M()->table(array('sdx_user_behavior_address'=>'uba'))
            ->where("uba.uid =".$uid)
            ->field("from_unixtime(uba.add_time,'%Y%m%d') as add_times")
            ->order("uba.add_time desc")
            ->limit("1")
            ->select();
        foreach ($is_continued_num as $values){
            $is_continued_num_25[] = $values['add_times'];
        }
        $is_continued_num_25 = array_unique($is_continued_num_25);
        //dump($is_continued_num_25);
        $yesterday_address = M()->table(array('sdx_user_behavior_browse'=>'uba'))
            ->where("uba.uid =".$uid)
            ->field("from_unixtime(uba.add_time,'%Y%m%d') as add_times")
            ->order("uba.add_time desc")
            ->limit("1")
            ->select();
        foreach ($yesterday_address as $values){
            $yesterday_address_25[] = $values['add_times'];
        }
        $yesterday_address_25 = array_unique($yesterday_address_25);
        //dump($yesterday_address_25);


        $old_give_array = array_unique(array_merge($is_continued_num_25,$yesterday_address_25));

        rsort($old_give_array);
        $continuousDays=0;
        $maxDay=$old_give_array[0];
        foreach($old_give_array as $item){
            if($item==$maxDay){
                $continuousDays++;
                $maxDay--;
            }else{
                break;
            }
        }


        $date['lastSignDate']=$old_give_array[0]?date("Y-m-d",strtotime($old_give_array[0])):'';
        $date['signCount']=$continuousDays;

        return $date;
    }



    /**
     * 今天第一次领取奖励的用户发送信息
     */
    private function auto_give_money_msg(){
        set_time_limit(0);
        $give_phone = array();

        $i=0;
        $give_list = M("account_log")->where("change_type = 8 AND TO_DAYS(from_unixtime(change_time)) = TO_DAYS(from_unixtime(unix_timestamp()-28800))")
            ->getField("user_id",true);
        //今天已经登录
        foreach ($give_list as $key=>$value){
            $give_num = M("account_log")->where("change_type = 8 AND user_id=".$value)->count();
            if($give_num==1){
                //发送信息
                $mobile_phone = M("users")->where(array("user_id"=>$value))->getField("mobile_phone");
                if($mobile_phone){
                    //是绑定手机号
                    $give_phone[$value] = $mobile_phone;
                }else{
                    //未绑定手机号/查询默认地址中的手机号
                    $give_phone[$value] = M("user_address")->where(array("user_id"=>$value,"default"=>1))->getField("mobile");
                }
                $i++;
            }

        }
        $give_phone = array_unique(array_filter($give_phone));
        $msg_opt = M("mail_templates")->where(array("template_code"=>"daily_rewards"))->getField("msg_opt");

        $msg_opt = str_replace("\r\n",",",$msg_opt);
        $msg_opt = explode(",",$msg_opt);

        $wechat_param['url']="https://w.shidexian.com/?index#/index?utm_source=GZHmrjl";
        $wechat_param['first']='尊敬的小主，您昨日的登录福利已妥妥投递，请注意查收~每天登录每天送。';
        $wechat_param['keyword2']=date("Y-m-d",strtotime("-1 day"));
        $wechat_param['keyword3']='1元';

        foreach ($give_phone as $key=>$phone){
            //发送信息到用户手机
            //echo "手机:".$value."</br>";
            $wechat_param['keyword1']=$phone;
            $jlamount=M("user_account")->where(array("user_id"=>$key,"admin_note"=>array("like","登录奖励%"),"is_paid"=>1))->sum("amount");
            $wechat_param['keyword4']='签到已累计奖励'.$jlamount.'元';
            A("Smsapi")->send_message_api("daily_rewards",$phone,$msg_opt[0],0,0,0,$key,array("goods_title"=>$msg_opt[1]),null,$wechat_param);
        }
    }




    /**
     * 领取过登录奖励，但是最近没有上线，则短信提醒  短信提醒频率为3天一次
     */
    public function urge_online_bonus(){
        set_time_limit(0);
        exit("stop");
    }

    /**
     * 发送指定红包到指定账户
     * @param $user_id
     * @param $bonus_type_id
     * @param $user_bonus
     * @param $bonus_type
     * @return bool
     */
    public function auto_send_bonus($user_id, $bonus_type_id,$user_bonus,$bonus_type){
        $where['user_id'] = $user_id;
        $where['bonus_type_id'] = $bonus_type_id;
        $send_log = $user_bonus->where($where)->count();
        if($send_log>0){
            return true;
        }

        //检查是否存储红包类型
        $bonus_type_info = S("bonus_type_info_".$bonus_type_id);
        if(empty($bonus_type_info)){
            $bonus_type_info= $bonus_type->field("has_effective_days,effective_days")->
            where(array("type_id"=>$bonus_type_id))->find();
            if(empty($bonus_type_info)){
                return false;
            }else{
                S("bonus_type_info_".$bonus_type_id,$bonus_type_info,86400);
            }
        }
        if($bonus_type_info['has_effective_days']==1 && $bonus_type_info['effective_days']>0){
            $end_time = time() + ($bonus_type_info['effective_days']-1)*24*3600;
            $end_date = date('Y-m-d',$end_time)." 23:59:59";
            $deadline = local_strtotime($end_date); //转换成GMT格林威治时间戳
        }else{
            $deadline = 0;
        }
        $bonus_sn = gmtime() . str_pad(mt_rand(0, 99999), 4, '0', STR_PAD_LEFT);
        $data['user_id'] = $user_id;
        $data['get_time'] = gmtime();
        $data['deadline'] = $deadline;
        $data['bonus_type_id'] = $bonus_type_id;
        $data['bonus_sn'] = $bonus_sn;
        $re = $user_bonus->add($data);
        if($re){
            return true;
        }else{
            return false;
        }

    }



    /**获取红包到达微信推送参数
     * @param $user_id
     * @param $bonus_type_id
     */
    private function send_bonus_arrived_sms_bak_all($user_id,$bonus_type_id=array(),$batch_bonus_text="专享红包到账了"){
        $nickname=M("wechat_user")->where(array("ect_uid"=>$user_id))->getField("nickname");
        $phone=M("users")->where(array("user_id"=>$user_id))->getField("mobile_phone");
        $bonus_type=M("bonus_type")->where(array("type_id"=>$bonus_type_id[0]))->Field("use_end_date")->find();

        $wechat_param=array();
        $wechat_param['url']="https://w.shidexian.com/?index#/bag";
        $wechat_param['keyword1']=$nickname;
        $wechat_param['keyword2']=array($batch_bonus_text,"#ff0000");
        $wechat_param['keyword3']=local_date("Y-m-d",$bonus_type['use_end_date']);


        $message_log_id=A("Smsapi")->send_message_api_asyn("bonus_arrived",$phone,$phone,0,0,0,$user_id,array(),null,$wechat_param);
        if($message_log_id && !empty($bonus_type_id)){
            foreach($bonus_type_id as $item){
                M("message_log_bonus")->data(array("message_id"=>$message_log_id,'bonus_type_id'=>$item))->add();
            }
        }
    }

    /**获取红包到达微信推送参数
     * @param $user_id
     * @param $bonus_type_id
     */
    private function send_bonus_arrived_sms_bak($user_id,$bonus_type_id=array()){
        $nickname=M("wechat_user")->where(array("ect_uid"=>$user_id))->getField("nickname");
        $phone=M("users")->where(array("user_id"=>$user_id))->getField("mobile_phone");

        $bonus_type=M("bonus_type")->where(array("type_id"=>$bonus_type_id[0]))->Field("bonus_discount_type,type_money,min_goods_amount,use_end_date")->find();

        $user_bonus=M("user_bonus")->where(array("user_id"=>$user_id,"bonus_type_id"=>$bonus_type_id[0]))->Field("deadline")->order("deadline desc")->find();

        if($bonus_type['bonus_discount_type']==1){
            $bonus_text='满'.$bonus_type['min_goods_amount'].'减'.$bonus_type['type_money'].'红包';
        }else if($bonus_type['bonus_discount_type']==2){
            $bonus_text=$bonus_type['type_money'].'折红包';
        }

        if($user_bonus['deadline']!=0){
            $user_use_end_date=local_date("Y-m-d",$user_bonus['deadline']);
        }else{
            $user_use_end_date=local_date("Y-m-d",$bonus_type['use_end_date']);
        }


        $wechat_param=array();
        $wechat_param['url']="https://w.shidexian.com/?index#/index";
        $wechat_param['keyword1']=$nickname;
        $wechat_param['keyword2']=$bonus_text.'等'.count($bonus_type_id).'个红包';
        $wechat_param['keyword3']=$user_use_end_date."到期";



        $message_log_id=A("Smsapi")->send_message_api("bonus_arrived",$phone,$phone,0,0,0,$user_id,array(),null,$wechat_param);
        if($message_log_id && !empty($bonus_type_id)){
            foreach($bonus_type_id as $item){
                M("message_log_bonus")->data(array("message_id"=>$message_log_id,'bonus_type_id'=>$item))->add();
            }

        }
    }

    private function send_bonus_arrived_sms($user_id,$bonus_type_id){
        $nickname='食得鲜用户';

        $nicknamea=M("wechat_user")->where(array("ect_uid"=>$user_id))->getField("nickname");

        $item=M("bonus_type")->where(array("type_id"=>$bonus_type_id))->Field("bonus_discount_type,type_money,min_goods_amount,use_end_date")->find();

        $user_bonus=M("user_bonus")->where(array("user_id"=>$user_id,"bonus_type_id"=>$bonus_type_id))->Field("deadline")->order("deadline desc")->find();

        if(!empty($nicknamea)){
            $nickname=$nicknamea;
        }

        if($item['deadline']!=0){
            $user_use_end_date=local_date("Y-m-d",$user_bonus['deadline']);
        }else{
            $user_use_end_date=local_date("Y-m-d",$item['use_end_date']);
        }

        $betweenSecond=strtotime($user_use_end_date)-strtotime(date("Y-m-d"));
        $dayS=$betweenSecond/(24*60*60);
        $dayS+=1;

        $keyword1='';
        if($item['bonus_discount_type']==1){
            $keyword1='满'.$item['min_goods_amount'].'减'.$item['type_money'].'红包';
        }elseif($item['bonus_discount_type']==2){
            $keyword1=$item['type_money'].'折红包';
        }

        $wechat_param['url']="https://w.shidexian.com/?index&utm_source=GZHbonus_expired_reminder";
        $wechat_param['first']='陪你那么久，不想留遗憾！';
        $wechat_param['keyword1']=$keyword1;
        $wechat_param['keyword2']=$user_use_end_date;
        $wechat_param['remark']='亲爱的主人，说好要做您的天使，可现在只能陪您最后'.$dayS.'天了！有效期内使用红包满减，让彼此不留遗憾';

        $remark=array();
        $remark['date']=$user_use_end_date;
        $remark['bonus_money']=$item['type_money'];
        $remark['min_amount']=$item['min_goods_amount'];

        $message_log_id=A("Smsapi")->send_message_api_asyn("bonus_expired_reminder",$item['mobile_phone'],$nickname,0,0,0,$user_id,$remark,null,$wechat_param,array(),$bonus_type_id);

        if($message_log_id && $bonus_type_id!=''){
            M("message_log")->where(array("message_id"=>$message_log_id))->save(array("bonus_type_id"=>$bonus_type_id));
        }
    }

    private function send_bonus_arrived_sms_asyn($user_id,$bonus_type_id){
        $nickname='食得鲜用户';

        $nicknamea=M("wechat_user")->where(array("ect_uid"=>$user_id))->getField("nickname");

        $item=M("bonus_type")->where(array("type_id"=>$bonus_type_id))->Field("bonus_discount_type,type_money,min_goods_amount,use_end_date")->find();

        $user_bonus=M("user_bonus")->where(array("user_id"=>$user_id,"bonus_type_id"=>$bonus_type_id))->Field("deadline")->order("deadline desc")->find();

        if(!empty($nicknamea)){
            $nickname=$nicknamea;
        }

        if($item['deadline']!=0){
            $user_use_end_date=local_date("Y-m-d",$user_bonus['deadline']);
        }else{
            $user_use_end_date=local_date("Y-m-d",$item['use_end_date']);
        }

        $betweenSecond=strtotime($user_use_end_date)-strtotime(date("Y-m-d"));
        $dayS=$betweenSecond/(24*60*60);
        $dayS+=1;

        $keyword1='';
        if($item['bonus_discount_type']==1){
            $keyword1='满'.$item['min_goods_amount'].'减'.$item['type_money'].'红包';
        }elseif($item['bonus_discount_type']==2){
            $keyword1=$item['type_money'].'折红包';
        }

        $wechat_param['url']="https://w.shidexian.com/?index&utm_source=GZHbonus_expired_reminder";
        $wechat_param['first']='陪你那么久，不想留遗憾！';
        $wechat_param['keyword1']=$keyword1;
        $wechat_param['keyword2']=$user_use_end_date;
        $wechat_param['remark']='亲爱的主人，说好要做您的天使，可现在只能陪您最后'.$dayS.'天了！有效期内使用红包满减，让彼此不留遗憾';

        $remark=array();
        $remark['date']=$user_use_end_date;
        $remark['bonus_money']=$item['type_money'];
        $remark['min_amount']=$item['min_goods_amount'];

        A("Smsapi")->send_message_api_asyn("bonus_expired_reminder",$item['mobile_phone'],$nickname,0,0,0,$user_id,$remark,null,$wechat_param,array(),$bonus_type_id);

    }


    public function ttt(){
        $batch_bonus_text = S("batch_bonus_text");
        if(empty($batch_bonus_text)){
            $batch_bonus_text = "专享红包到账啦";
        }
        $this->send_bonus_arrived_sms_bak_all(1980,array(817),$batch_bonus_text);
    }


    /**
     * 创建所需发送红包的用户
     * Author:poptser@foxmail.com
     */
    public function create_all_user(){

        $user_list = M("users")->where("user_name not like 'wx_196%'")->getField("user_id",true);
        S("bonus_send_user",$user_list,28800);  //保存8小时，发送红包数据组
        S("bonus_msg_user",$user_list,28800);   //保存8小时，发送推送信息组
        echo count($user_list);
    }

    /**
     * 发送红包
     * Author:poptser@foxmail.com
     */
    public function start_send_bonus(){
        set_time_limit(0);
        header("Content-type: text/html; charset=utf-8");
        $run_bonus = S("run_bonus_all");
        if(!empty($run_bonus)){
            exit("请勿重复运行,发放已结束");
        }else{
            S("run_bonus_all",999,10);
        }
        $user_array = S("bonus_send_user");
//        dump($user_array);
//        exit();
//        $this->assign("user_num",count($user_array));
//        $this->assign("data_time",date('Y-m-d h:i:s', time()));
//        $this->display('test');
//        exit();
        $bonus_type = M("bonus_type");
        $user_bonus = M("user_bonus");

        $now_send = array_slice($user_array,0,50000);
        $new_array = array_diff($user_array,$now_send);
        S('bonus_send_user',$new_array);
        $bonus_type_str = S("batch_bonus_id");
        $bonus_type_array = explode(",",$bonus_type_str);
        foreach ($now_send as $key=>$value){
            foreach ($bonus_type_array as $bonus_type_id){
                $this->auto_send_bonus($value,$bonus_type_id,$user_bonus,$bonus_type);
            }

        }
        $this->assign("user_num",count($new_array));
        $this->assign("data_time",date('Y-m-d h:i:s', time()));
        $this->display('test');
    }

    /**
     * 发送红包通知
     * Author:poptser@foxmail.com
     */
    public function start_send_msg(){
        set_time_limit(0);
        header("Content-type: text/html; charset=utf-8");
        $run_bonus = S("run_bonus_all_s");
        if(!empty($run_bonus)){
            exit("请勿重复运行,发放已结束");
        }else{
            S("run_bonus_all_s",999,10);
        }
        $batch_bonus_text = S("batch_bonus_text");
        if(empty($batch_bonus_text)){
            $batch_bonus_text = "专享红包到账啦";
        }

        $all_bonus_list = S('bonus_msg_user');
//        $this->assign("user_num",count($all_bonus_list));
//        $this->assign("data_time",date('Y-m-d h:i:s', time()));
//        $this->display('test');
//        exit();
        $now_send = array_slice($all_bonus_list,0,700);
        $new_array = array_diff($all_bonus_list,$now_send);

        S('bonus_msg_user',$new_array,28800);
        $bonus_type_str = S("batch_bonus_id");
        $bonus_type_array = explode(",",$bonus_type_str);
        foreach ($now_send as $key=>$value){
            $this->send_bonus_arrived_sms_bak_all($value,$bonus_type_array,$batch_bonus_text);
        }
        $this->assign("user_num",count($new_array));
        $this->assign("data_time",date('Y-m-d h:i:s', time()));
        $this->display('test');
    }
    /**
     * 发送红包
     */
    public function test_new(){
        set_time_limit(0);
        header("Content-type: text/html; charset=utf-8");
        exit('此活动已停止');
        $week = date("w");
        $run_dir = "order_xls/bonus_fail/run_log";
        $now_hour = date('H',time()).date('i',time());

        if($week==0||$week==6){
            if($now_hour<900||$now_hour>1600){
                //周末，9点开始
                $this->write_fail($run_dir,date('Y-m-d H:i:s')." time err 1");
                exit('time err 1 '.$week);
            }
        }else{
            if($now_hour<830||$now_hour>1600){
                //工作日，8点30开始
                $this->write_fail($run_dir,date('Y-m-d H:i:s')." time err 2");
                exit('time err 2'.$week);
            }
        }


        $run_bonus = S("run_bonus");
        if(!empty($run_bonus)){
            $this->write_fail($run_dir,date('Y-m-d H:i:s')." time err");
            exit("请勿重复运行");
        }else{
            S("run_bonus",999,10);
        }

        //S("op_run_time",null);

        $op_run_time = S("op_run_time");
        $new_data = false;
        if($op_run_time){
            $a_date = date('Y-m-d',$op_run_time['time']);
            $b_date = date('Y-m-d');
            if($a_date==$b_date){
                if($op_run_time['status']==1){
                    //开始运行  生成数据
                    $new_data = true;
                }
                if($op_run_time['status']==2){
                    //运行中  直接读取数据
                    $new_data = false;
                }
                if($op_run_time['status']==3){
                    exit("已运行完成");
                }
            }else{
                $run_time = array(
                    "time"=>time(),
                    "status" => 1 //开始运行
                );
                $new_data = true;
                //开始运行  生成数据
                S("op_run_time",$run_time);
            }
        }else{
            //无数据，首次运行
            $run_time = array(
                "time"=>time(),
                "status" => 1 //开始运行
            );
            $new_data = true;
            //开始运行  生成数据
            S("op_run_time",$run_time);
        }

        if ($new_data){
            // 开始运行  生成数据
            switch ($week){
                case 0:
                    //星期天
                    $activity_id = 7;
                    break;
                case 1:
                    $activity_id = 1;
                    //星期一
                    break;
                case 2:
                    $activity_id = 2;
                    break;
                case 3:
                    $activity_id = 3;
                    break;
                case 4:
                    $activity_id = 4;
                    break;
                case 5:
                    $activity_id = 5;
                    break;
                case 6:
                    $activity_id = 6;
                    break;
                default:
                    return false;
            }
            $active_user = $this->get_expired_user($week);  //

            $blacklist = array(60583,71210,860417,648405);      //红包黑名单

            $user_list = array_diff($user_list,$blacklist);

            S("user_list",$user_list,86400);
            $user_array = S("user_list");

            //数据已生成
            $run_time = array(
                "time"=>time(),
                "status" => 2 //运行中
            );
            S("op_run_time",$run_time);
        }else{
            //继续运行 不生成数据
            $user_array = S("user_list");
        }

        //$user_array = array(4228,1980,198);

        $i = 0;
        //$bonus_type_array = array(244,245,246,247);   //此次发送的红包ID 244,245,246,247


        $bonus_str = M("ticket_set")->where(array("id"=>2))->getField("text");

        if(empty($bonus_str)){
            $this->send_dingtalk_ts("每天运营红包设置数据出错，未设置发送红包");
            exit();
        }
        $bonus_type_array = explode(",",$bonus_str);
        //$bonus_type_array = array(266,265,264,263);   //此次发送的红包ID  258、259、260、261
        $user_bonus = M("user_bonus");
        $bonus_type = M("bonus_type");

        $this->write_fail($run_dir,date('Y-m-d H:i:s')." runing...");

        foreach ($user_array as $key=>$value){
            $i++;
            if($i==3000){
                $this->write_fail($run_dir,date('Y-m-d H:i:s')." send 3000 ,Still left:".count($user_array));
                exit();
            }else{
                $j=0;
                foreach ($bonus_type_array as $keys=>$bonus_type_id){
                    $count_new = $user_bonus->where(array("bonus_type_id"=>$bonus_type_id,"user_id"=>$value))->count('bonus_id');
                    if(empty($count_new)){
                        $send_bonus = $this->auto_send_bonus($value,$bonus_type_id,$user_bonus,$bonus_type);
                        if($send_bonus){
                            $j++;   //发送成功计数
                        }else{
                            //unset($bonus_type_array[$keys]);
                        }
                    }
                }
                //已发送此类红包
                unset($user_array[$key]);
                S('user_list',$user_array);
                //S('user_list',$user_array);
                if($j>0){
                    try{
                        $this->send_bonus_arrived_sms_bak($value,$bonus_type_array);
                    }catch (Exception $e){
                        $this->write_fail($run_dir,date('Y-m-d H:i:s')." send bonus sms fail..".$e->getMessage());
                    }

                }
            }
        }
        //exit();
        if(empty($user_array)){
            $run_time = array(
                "time"=>time(),
                "status" => 3 //运行完成
            );
            $this->write_fail($run_dir,date('Y-m-d H:i:s')." send all");
            $this->show_fail_user($bonus_type_array[0]); //显示本次失败手机号
            S("op_run_time",$run_time);
        }
        //全部红包已经发放
    }
    /**
     * 发送红包
     */
    public function test_s(){
        set_time_limit(0);
        header("Content-type: text/html; charset=utf-8");
        exit('此活动已停止');
        $week = date("w");
        $run_dir = "order_xls/bonus_fail/run_log";
        $now_hour = date('H',time()).date('i',time());

        if($week==0||$week==6){
            if($now_hour<900||$now_hour>1600){
                //周末，9点开始
                $this->write_fail($run_dir,date('Y-m-d H:i:s')." time err 1");
                exit('time err 1 '.$week);
            }
        }else{
            if($now_hour<830||$now_hour>1600){
                //工作日，8点30开始
                $this->write_fail($run_dir,date('Y-m-d H:i:s')." time err 2");
                exit('time err 2'.$week);
            }
        }


        $run_bonus = S("run_bonus");
        if(!empty($run_bonus)){
            $this->write_fail($run_dir,date('Y-m-d H:i:s')." time err");
            exit("请勿重复运行");
        }else{
            S("run_bonus",999,10);
        }
        /**
         *    周五   active_user_list_5  unactive_user_list_5
         *    周六   active_user_list_6  unactive_user_list_6
         *    周日   active_user_list_7  unactive_user_list_7
         *    周一   active_user_list_8  unactive_user_list_8
         *    周二   active_user_list_9  unactive_user_list_9
         *    周三   active_user_list_10 unactive_user_list_10
         *    周四   active_user_list_11 unactive_user_list_11
         */

        //S("op_run_time",null);

        $op_run_time = S("op_run_time");
        $new_data = false;
        if($op_run_time){
            $a_date = date('Y-m-d',$op_run_time['time']);
            $b_date = date('Y-m-d');
            if($a_date==$b_date){
                if($op_run_time['status']==1){
                    //开始运行  生成数据
                    $new_data = true;
                }
                if($op_run_time['status']==2){
                    //运行中  直接读取数据
                    $new_data = false;
                }
                if($op_run_time['status']==3){
                    exit("已运行完成");
                }
            }else{
                $run_time = array(
                    "time"=>time(),
                    "status" => 1 //开始运行
                );
                $new_data = true;
                //开始运行  生成数据
                S("op_run_time",$run_time);
            }
        }else{
            //无数据，首次运行
            $run_time = array(
                "time"=>time(),
                "status" => 1 //开始运行
            );
            $new_data = true;
            //开始运行  生成数据
            S("op_run_time",$run_time);
        }

        if ($new_data){
            // 开始运行  生成数据
            switch ($week){
                case 0:
                    //星期天
                    $activity_id = 7;
                    break;
                case 1:
                    $activity_id = 8;
                    //星期一
                    break;
                case 2:
                    $activity_id = 9;
                    break;
                case 3:
                    $activity_id = 10;
                    break;
                case 4:
                    $activity_id = 11;
                    break;
                case 5:
                    $activity_id = 5;
                    break;
                case 6:
                    $activity_id = 6;
                    break;
                default:
                    return false;
            }
            $active_user = $this->get_new_user($week);  //含新用户的活跃用户
            $user_list = array_merge($active_user,S("unactive_user_list_".$activity_id));

            $blacklist = array(60583,71210,860417,648405);      //红包黑名单

            $user_list = array_diff($user_list,$blacklist);

            S("user_list",$user_list,86400);
            $user_array = S("user_list");

            //数据已生成
            $run_time = array(
                "time"=>time(),
                "status" => 2 //运行中
            );
            S("op_run_time",$run_time);
        }else{
            //继续运行 不生成数据
            $user_array = S("user_list");
        }

        //$user_array = array(1980);

        $i = 0;
        //$bonus_type_array = array(244,245,246,247);   //此次发送的红包ID 244,245,246,247


        $bonus_str = M("ticket_set")->where(array("id"=>2))->getField("text");

        if(empty($bonus_str)){
            $this->send_dingtalk_ts("每天运营红包设置数据出错，未设置发送红包");
            exit();
        }
        $bonus_type_array = explode(",",$bonus_str);
        //$bonus_type_array = array(266,265,264,263);   //此次发送的红包ID  258、259、260、261
        $user_bonus = M("user_bonus");
        $bonus_type = M("bonus_type");

        $this->write_fail($run_dir,date('Y-m-d H:i:s')." runing...");

        foreach ($user_array as $key=>$value){
            $i++;
            if($i==3000){
                $this->write_fail($run_dir,date('Y-m-d H:i:s')." send 3000 ,Still left:".count($user_array));
                exit();
            }else{
                $j=0;
                foreach ($bonus_type_array as $keys=>$bonus_type_id){
                    $count_new = $user_bonus->where(array("bonus_type_id"=>$bonus_type_id,"user_id"=>$value))->count('bonus_id');
                    if(empty($count_new)){
                        $send_bonus_s = S("auto_send_bonus_".$value."_".$bonus_type_id);
                        if(empty($send_bonus_s)){
                            $new_users = M("order_info")->where(array("user_id"=>$value,"shipping_status"=>2))->count('order_id');
                            if(empty($new_users)){
                                //新用户
                                $bonus_now_user = $user_bonus->
                                where("`bonus_type_id` IN(359, 358, 357, 355) AND `order_id` = 0 AND 
                                `user_id` = ".$value." AND(`order_id`> 0 OR `deadline`< unix_timestamp(now()))")
                                    ->count('bonus_id');
                                if(!empty($bonus_now_user)){
                                    //已使用或已过期
                                    $this->auto_send_bonus($value,$bonus_type_id,$user_bonus,$bonus_type);
                                    $j++;
                                }else{
                                    //未使用
                                }
                            }else{
                                //非新，直接发放红包
                                $this->auto_send_bonus($value,$bonus_type_id,$user_bonus,$bonus_type);
                                $j++;
                            }
                        }
                    }
                }
                //已发送此类红包
                unset($user_array[$key]);
                S('user_list',$user_array);
                //S('user_list',$user_array);
                if($j>0){
                    try{
                        $this->send_bonus_arrived_sms_bak($value,$bonus_type_array);
                    }catch (Exception $e){
                        $this->write_fail($run_dir,date('Y-m-d H:i:s')." send bonus sms fail..".$e->getMessage());
                    }

                }
            }
        }
        //exit();
        if(empty($user_array)){
            $run_time = array(
                "time"=>time(),
                "status" => 3 //运行完成
            );
            $this->write_fail($run_dir,date('Y-m-d H:i:s')." send all");
            $this->show_fail_user($bonus_type_array[0]); //显示本次失败手机号
            S("op_run_time",$run_time);
        }
        //全部红包已经发放
    }
    /**
     * 生成新未使用了红包或者已过期的用户
     * @param bool $week 星期
     * @return bool|mixed 含新用户的活跃用户
     */
    public function get_expired_user($week=false){
        /**
         * 新用户数据生成，获取所有用户，然后排除现有存在的用户
         */
        $user_model = M("users");

        //获取当前所有记录用户
        $all_action = array();

        $action_bonus_20171123_7 = S('action_bonus_20171123_7');
        if($action_bonus_20171123_7){
            $all_action = $action_bonus_20171123_7;
        }
        $action_bonus_20171123_1 = S('action_bonus_20171123_1');
        if($action_bonus_20171123_1){
            $all_action = array_merge($all_action,$action_bonus_20171123_1);
        }
        $action_bonus_20171123_2 = S('action_bonus_20171123_2');
        if($action_bonus_20171123_2){
            $all_action = array_merge($all_action,$action_bonus_20171123_2);
        }
        $action_bonus_20171123_3 = S('action_bonus_20171123_3');
        if($action_bonus_20171123_3){
            $all_action = array_merge($all_action,$action_bonus_20171123_3);
        }
        $action_bonus_20171123_4 = S('action_bonus_20171123_4');
        if($action_bonus_20171123_4){
            $all_action = array_merge($all_action,$action_bonus_20171123_4);
        }
        $action_bonus_20171123_5 = S('action_bonus_20171123_5');
        if($action_bonus_20171123_5){
            $all_action = array_merge($all_action,$action_bonus_20171123_5);
        }
        $action_bonus_20171123_6 = S('action_bonus_20171123_6');
        if($action_bonus_20171123_6){
            $all_action = array_merge($all_action,$action_bonus_20171123_6);
        }


        $all_now_user = M("user_bonus")->where("`bonus_type_id` IN(359, 358, 357, 355) AND `user_id`> 0
   AND(`order_id`> 0
    OR `deadline`< unix_timestamp(now()))")->group("user_id")->getField("user_id",true);
        $new_user = array_diff($all_now_user,$all_action);
        $return_data = array();
        switch ($week){
            case 0:
                //星期天
                $action_bonus_20171123_7 = S('action_bonus_20171123_7');
                if($action_bonus_20171123_7){
                    $my_action = array_merge($new_user,$action_bonus_20171123_7);
                    S('action_bonus_20171123_7',$my_action,260000); //保存一个月，一个月无使用删除数据
                    $return_data= $my_action;
                }else{
                    S('action_bonus_20171123_7',$action_bonus_20171123_7,260000);
                    $return_data= $action_bonus_20171123_7;
                }
                break;
            case 1:
                //星期一
                $action_bonus_20171123_1 = S('action_bonus_20171123_1');
                if($action_bonus_20171123_1){
                    $my_action = array_merge($new_user,$action_bonus_20171123_1);
                    S('action_bonus_20171123_1',$my_action,260000); //保存一个月，一个月无使用删除数据
                    $return_data= $my_action;
                }else{
                    S('action_bonus_20171123_1',$action_bonus_20171123_1,260000);
                    $return_data= $action_bonus_20171123_1;
                }
                break;
            case 2:
                //星期二
                $action_bonus_20171123_2 = S('action_bonus_20171123_2');
                if($action_bonus_20171123_2){
                    $my_action = array_merge($new_user,$action_bonus_20171123_2);
                    S('action_bonus_20171123_2',$my_action,260000); //保存一个月，一个月无使用删除数据
                    $return_data= $my_action;
                }else{
                    S('action_bonus_20171123_2',$action_bonus_20171123_2,260000);
                    $return_data= $action_bonus_20171123_2;
                }
                break;
            case 3:
                //星期三
                $action_bonus_20171123_3 = S('action_bonus_20171123_3');
                if($action_bonus_20171123_3){
                    $my_action = array_merge($new_user,$action_bonus_20171123_3);
                    S('action_bonus_20171123_3',$my_action,260000); //保存一个月，一个月无使用删除数据
                    $return_data= $my_action;
                }else{
                    S('action_bonus_20171123_3',$action_bonus_20171123_3,260000);
                    $return_data= $action_bonus_20171123_3;
                }
                break;
            case 4:
                //星期四
                $action_bonus_20171123_4 = S('action_bonus_20171123_4');
                if($action_bonus_20171123_4){
                    $my_action = array_merge($new_user,$action_bonus_20171123_4);
                    S('action_bonus_20171123_4',$my_action,260000); //保存一个月，一个月无使用删除数据
                    $return_data= $my_action;
                }else{
                    S('action_bonus_20171123_4',$action_bonus_20171123_4,260000);
                    $return_data= $action_bonus_20171123_4;
                }
                break;
            case 5:
                //星期五
                $action_bonus_20171123_5 = S('action_bonus_20171123_5');
                if($action_bonus_20171123_5){
                    $my_action = array_merge($new_user,$action_bonus_20171123_5);
                    S('action_bonus_20171123_5',$my_action,260000); //保存一个月，一个月无使用删除数据
                    $return_data= $my_action;
                }else{
                    S('action_bonus_20171123_5',$action_bonus_20171123_5,260000);
                    $return_data= $action_bonus_20171123_5;
                }
                break;
            case 6:
                //星期六
                $action_bonus_20171123_6 = S('action_bonus_20171123_6');
                if($action_bonus_20171123_6){
                    $my_action = array_merge($new_user,$action_bonus_20171123_6);
                    S('action_bonus_20171123_6',$my_action,260000); //保存一个月，一个月无使用删除数据
                    $return_data= $my_action;
                }else{
                    S('action_bonus_20171123_6',$action_bonus_20171123_6,260000);
                    $return_data= $action_bonus_20171123_6;
                }
                break;
            default:
                return false;
        }

        return $return_data;
    }
    /**
     * 生成新用户数据并合并到活跃用户中
     * @param bool $week 星期
     * @return bool|mixed 含新用户的活跃用户
     */
    public function get_new_user($week=false){
        /**
         * 新用户数据生成
         */
        $user_model = M("users");
        $data['is_active'] = 1;
        switch ($week){
            case 0:
                //星期天
                $data['activity_id'] = 7;
                $last_activity_id = 6;
                break;
            case 1:
                //星期一
                $data['activity_id'] = 8;
                $last_activity_id = 7;
                break;
            case 2:
                $data['activity_id'] = 9;
                $last_activity_id = 8;
                break;
            case 3:
                $data['activity_id'] = 10;
                $last_activity_id = 9;
                break;
            case 4:
                $data['activity_id'] = 11;
                $last_activity_id = 10;
                break;
            case 5:
                $data['activity_id'] = 5;
                $last_activity_id = 11;
                break;
            case 6:
                $data['activity_id'] = 6;
                $last_activity_id = 5;
                break;
            default:
                return false;
        }


        $last_user_id = $user_model->where(array("activity_id"=>$last_activity_id))
            ->order("user_id desc")->getField("user_id");

        $user_list = $user_model->where("user_id > ".$last_user_id." and user_name not like 'wx_196%'")
            ->getField("user_id",true);

        M("users")->where(array("user_id"=>array("in",$user_list)))->save($data);


        $active_user_list = S("active_user_list_".$data['activity_id']);

        $active_and_new = array_merge($active_user_list,$user_list);

        S("active_user_list_".$data['activity_id'],$active_and_new);

        return $active_and_new;
    }


    /**
     * 显示推送失败
     * @param bool $bonus_type_id
     */
    public function show_fail_user($bonus_type_id = false){

        if($bonus_type_id===false){
            exit("未能显示推送失败用户");
        }

        $give_phone = array();

        $user_list_b = M()->table(array('sdx_message_log'=>'ml','sdx_message_log_bonus'=>'mlb'))
            ->where("ml.message_id = mlb.message_id and mlb.bonus_type_id = {$bonus_type_id} and ml.wechat_state != 1
            and TO_DAYS(ml.send_time) = TO_DAYS(from_unixtime(unix_timestamp()))")->field("ml.user_id")->select();

        foreach ($user_list_b as $value){
            $user_list[] = $value['user_id'];
        }

        $user_list = array_unique($user_list);

        foreach ($user_list as $value){
            //echo $value."<hr>";
            $mobile_phone = M("users")->where(array("user_id"=>$value))->getField("mobile_phone");

            if($mobile_phone){
                array_push($give_phone,$mobile_phone);
            }

            $give_phone_array_one = M("user_address")->where(array("user_id"=>$value))->getField("mobile",true);
            if($give_phone_array_one){
                foreach ($give_phone_array_one as $one_phone){
                    array_push($give_phone,$one_phone);
                }
            }

        }
        $give_phone = array_unique($give_phone);

        //不发送信息列表
        $no_array = array(
            18028582275,18820013479,18903012888,13423621976,13922303379,
            13435247596,18588734970,15989012380,15920425953,13286800382,
            13926192875,18825163342,18588677281,13074215090
        );

        $file_dir = "order_xls/bonus_fail/send_".date("Ymd")."_".rand(00000,99999);
        foreach ($give_phone as $value){
            if(!empty($value)&&!in_array($value,$no_array)){
                $this->write_fail($file_dir,$value);
            }

        }
        $file_dir_ok = $file_dir.".txt";
        if(is_file($file_dir_ok)){
            //发送文件
            $this->send_dingtalk_msg($file_dir_ok);
        }
    }

    public function write_fail($filename=null,$text){
        $open=fopen($filename.".txt","a" );
        fwrite($open,$text."\r\n");
        fclose($open);
    }
    /**
     * 发送钉钉信息
     * @param $test
     */
    public function send_dingtalk_ts($test="错误的消息"){
        return false;//停止发送
        $webhook = "https://oapi.dingtalk.com/robot/send?access_token=7957d5ece705a3be9674ec4a4b3293e285ebd00497c9c0cc4be86de8cd2f0409";
        $send_msg2 =
            array(
                "msgtype"=>"text",
                "text"=>array(
                    "content"=>$test
                ),
                "at"=>array(
                    "atMobiles"=>array("13222782015"),
                    "isAtAll"=>false
                )
            );
        $data_string = json_encode($send_msg2);
        $result = $this->request_by_curl($webhook, $data_string);
    }
    /**
     * 发送钉钉信息
     * @param $file_dir_ok
     */
    public function send_dingtalk_msg($file_dir_ok){
        $webhook = "https://oapi.dingtalk.com/robot/send?access_token=7957d5ece705a3be9674ec4a4b3293e285ebd00497c9c0cc4be86de8cd2f0409";
        $send_msg2 =
        array(
            "msgtype"=>"actionCard",
            "actionCard"=>array(
                "text"=>"![screenshot](http://pic.qqtn.com/up/2016-7/201607281021086348524.png) 
 ### ".date('Y-m-d', time())." 红包失败记录
 数据当天有效，当天下载，通过短信平台发送信息",
                "title"=>date('Y-m-d', time())." 红包发送失败记录",
                "hideAvatar"=>"0",
                "btnOrientation"=>"0",
                "btns"=>array(
                    array(
                        "title"=>"点击查看",
                        "actionURL"=>"https://api.shidexian.com/".$file_dir_ok
                    )
                )
            )
        );
        $data_string = json_encode($send_msg2);
        $result = $this->request_by_curl($webhook, $data_string);
    }

    public function auto_check_bonus_number(){
        set_time_limit(0);
        $bonusService = new BonusService();
        $bonusService->checkVirtualNumber();
    }

    public function request_by_curl($remote_server, $post_string) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}

